package org.fastsyncer.rest.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.common.entity.LdapConfig;
import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.common.entity.WebServiceConfig;
import org.fastsyncer.common.util.JsonUtil;
import org.fastsyncer.framework.connector.ConnectorService;
import org.fastsyncer.framework.manager.ManagerService;
import org.fastsyncer.rest.common.ThridpartAppHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/driver")
public class DriverController {

	private static final Logger logger = LoggerFactory.getLogger(DriverController.class);

	@RequestMapping("/page/{opr}")
	public String driverAdd(HttpServletRequest request, ModelMap model, @PathVariable("opr") String opr, @RequestParam(value = "driverId", required = false) String driverId) {
		if (!StringUtils.isBlank(driverId)) {
			try {
				Object driver = ManagerService.getInstance().getDriver(driverId);
				model.addAttribute("dirver", driver);
				model.addAttribute("dirverJson", JsonUtil.objToJson(driver));
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage(), e.getClass());
			}
		}
		
		//如果是新增请求
		if("driverAdd".equals(opr)){
			ThridpartAppHandler.checkSessionAppid(request);
		}
		return "driver/" + opr;
	}

	@RequestMapping(value = "/getDatabaseConnector", method = RequestMethod.POST)
	@ResponseBody
	public RestResult getDatabaseConnector(HttpServletResponse response, DatabaseConfig config) {
		try {
			return RestResult.restSuccess(ConnectorService.getInstance().getBaseInfoConnector(ConnectorConstant.DB_CONNECTOR, config));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail("配置失败, 请检查参数.");
		}
	}
	
	@RequestMapping(value = "/getLdapConnector", method = RequestMethod.POST)
	@ResponseBody
	public RestResult getLdapConnector(HttpServletResponse response, LdapConfig config) {
		try {
			return RestResult.restSuccess(ConnectorService.getInstance().getBaseInfoConnector(ConnectorConstant.LDAP_CONNECTOR, config));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("配置失败, 请检查参数.");
		}
	}
	
	@RequestMapping(value = "/getWebserviceConnector", method = RequestMethod.POST)
	@ResponseBody
	public RestResult getWebserviceConnector(HttpServletResponse response, WebServiceConfig config) {
		try {
			return RestResult.restSuccess(ConnectorService.getInstance().getBaseInfoConnector(ConnectorConstant.WS_CONNECTOR, config));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
            return RestResult.restFail("配置失败, 请检查参数.");
		}
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public RestResult add(HttpServletRequest request, @RequestParam(value = "mapping") String mapping) {
		try {
			logger.info(mapping);
			if (StringUtils.isBlank(mapping)) {
				throw new NullPointerException("mapping参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().add(mapping));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public RestResult update(HttpServletResponse response, @RequestParam(value = "mapping") String mapping) {
		try {
			logger.info(mapping);
			if (StringUtils.isBlank(mapping)) {
				throw new NullPointerException("mapping参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().update(mapping));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}

	@RequestMapping(value = "/enable", method = RequestMethod.POST)
	@ResponseBody
	public RestResult enable(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("name参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().enable(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/disable", method = RequestMethod.POST)
	@ResponseBody
	public RestResult disable(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("name参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().disable(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}

	@RequestMapping(value = "/start", method = RequestMethod.POST)
	@ResponseBody
	public RestResult start(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().start(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/stop", method = RequestMethod.POST)
	@ResponseBody
	public RestResult stop(HttpServletResponse response, @RequestParam(value = "driverId") String id) {
		try {
			if (StringUtils.isBlank(id)) {
				throw new NullPointerException("参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().stop(id));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public RestResult delete(HttpServletResponse response, @RequestParam(value = "driverId") String driverId) {
		try {
			if (StringUtils.isBlank(driverId)) {
				throw new NullPointerException("参数不能为空！");
			}
			return RestResult.restSuccess(ManagerService.getInstance().delete(driverId));
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
			return RestResult.restFail(e.getLocalizedMessage());
		}
	}

	@RequestMapping("/download")
	public String download(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "dirverId") String id) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName=" + id + ".txt");
		
		InputStream is = null;
		ServletOutputStream os = null;
		try {
			File log = ManagerService.getInstance().getMappingLog(id);
			if(log!=null){
			    is = new FileInputStream(log);
			    if(is!=null){
			        os = response.getOutputStream();
			        byte[] b = new byte[2048];
			        int length;
			        while ((length = is.read(b)) > 0) {
			            os.write(b, 0, length);
			        }
			    }
			}
		} catch (FileNotFoundException e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
		} catch (IOException e) {
			logger.error(e.getLocalizedMessage(), e.getClass());
		} finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
		return null;
	}

}
